package com.mhg.socket;

import java.net.*;
import java.io.*;
//发送端 键盘录入
class Demo_02_Udp_Send 
{
	public static void main(String[] args) throws Exception
	{
		//1.创建Socket服务
		DatagramSocket socket = new DatagramSocket();
		//2.创建键盘录入
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		//3.获取键盘录入的数据 并且 将其 打包 发送
		String line = null;
		while((line = br.readLine())!=null){
			if("886".equals(line)){
				break;
			}
			byte[] buf = line.getBytes();
			//打包
			DatagramPacket packet = new DatagramPacket(
				buf,buf.length,InetAddress.getByName("127.0.0.1"),10001);
			//发送
			socket.send(packet);
		}
		//4.关闭资源
		socket.close();
		System.out.println("success");
	}
}
//接收端
class Demo_02_Udp_Receive
{
	public static void main(String[] args) throws Exception{
		//1.创建Socket服务
		DatagramSocket socket = new DatagramSocket(10001);
		//2.获取数据
		while(true){
			byte[] buf = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buf,buf.length);
			//3.获取数据包中的数据
			socket.receive(packet);
			//4.输出数据
			String ip = packet.getAddress().getHostAddress();
			String data = new String(packet.getData(),0,packet.getLength());
			System.out.println(ip+"...."+data);
		}
		
	}
}